//
//  SceneViewController.m
//  SelfDriving
//  场景
//  Created by apple on 15/12/1.
//  Copyright © 1515年 apple. All rights reserved.
//

#import "SceneViewController.h"
#import <CoreLocation/CoreLocation.h>
#import <AVFoundation/AVFoundation.h>
#import "MyLatLng.h"
#import "SphereMenu.h"
#import "FriendDetailsMainVC.h"
#import "BusinessService+User.h"
#import "ChatViewController.h"
#import "BusinessService+FJ.h"
@interface SceneViewController ()<CLLocationManagerDelegate,UIActionSheetDelegate,SphereMenuDelegate,UIActionSheetDelegate,UICollectionViewDelegate,UICollectionViewDataSource>
@property (strong, nonatomic) UIImageView *arrowImageView;

@property ( strong , nonatomic ) AVCaptureDevice * device;
@property ( strong , nonatomic ) AVCaptureDeviceInput * input;
@property ( strong , nonatomic ) AVCaptureMetadataOutput * output;
@property ( strong , nonatomic ) AVCaptureSession * session;
@property ( strong , nonatomic ) AVCaptureVideoPreviewLayer * preview;


//collectionView 滑动模拟旋转扫描
@property(nonatomic, strong) UICollectionView *collectionView;
@property(nonatomic, strong) NSMutableArray *views;
@property(nonatomic, assign) CGFloat jiaoduToOffset;

@end

@implementation SceneViewController{
    CLLocationManager *locationManager;
    NSMutableArray *ary;
    
    NSMutableArray *d;
    NSMutableArray *db;
    NSMutableArray *b;
    NSMutableArray *xb;
    NSMutableArray *x;
    NSMutableArray *xn;
    NSMutableArray *n;
    NSMutableArray *dn;

    UIImageView *mapview;
    UILabel *la;
    NSMutableDictionary *map;
}
-(void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBarHidden = YES;
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [[NSNotificationCenter defaultCenter ]postNotificationName:@"hidemenu" object:@"1"];
}
-(CGPoint)calcCircleCoordinateWithCenter:(CGPoint) center  andWithAngle : (CGFloat) angle andWithRadius: (CGFloat) radius{
    CGFloat x2 = radius*cosf(angle*M_PI/180);
    CGFloat y2 = radius*sinf(angle*M_PI/180);
    return CGPointMake(center.x+x2, center.y-y2);
}
-(int)getRandomNumber:(int)from to:(int)to
{
    return (int)(from + (arc4random() % (to - from + 1)));
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    // 设置UICollectionView为横向滚动
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:flowLayout];
    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"ImageCell"];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = UIColorClear;
    self.collectionView.scrollEnabled = NO;
    [self.view addSubview:self.collectionView];

    ary = _ary;
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(SCRE_WIDTH-90, 20, 80, 80)];
    
    mapview = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 80, 80)];
    mapview.image = [UIImage imageNamed:@"leida"];
    [view addSubview:mapview];
    la = [[UILabel alloc]initWithFrame:CGRectMake(80, 40, 40, 20)];
    la.textColor = [UIColor whiteColor];
    la.font = [UIFont systemFontOfSize:10];
    //    [self.view addSubview:la];
    mapview.layer.cornerRadius = mapview.frame.size.width/2;
    mapview.backgroundColor = [UIColor blackColor];
    mapview.layer.opacity = 0.7;
    _arrowImageView = [[UIImageView alloc]initWithFrame:CGRectMake(40, 0, 39, 44)];
    _arrowImageView.image = [UIImage imageNamed:@"leidasm"];
    [view addSubview:_arrowImageView];
    [self.view addSubview:view];
    
    
    locationManager= [[CLLocationManager alloc]init];
    locationManager.delegate = self;
    // 如果磁力计可用，则开始监听方向改变
    if ([CLLocationManager headingAvailable]) {
        //设置精度
        locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        //设置滤波器不工作
//        locationManager.headingFilter = 100;
        //开始更新
        [locationManager startUpdatingHeading];
    }
    // 如果磁力计不可用，则使用UIAlertView显示提示信息
    else
    {
        // 使用警告框提醒用户
        [[[UIAlertView alloc] initWithTitle:@"提醒"
                                    message:@"您的设备不支持磁力计" delegate:self
                          cancelButtonTitle:@"确定" otherButtonTitles: nil]
         show];
    }
    
    // Device
    _device = [ AVCaptureDevice defaultDeviceWithMediaType : AVMediaTypeVideo ];
    // Input
    NSError *error = nil;
    _input = [ AVCaptureDeviceInput deviceInputWithDevice : self . device error : &error];
    // Output
    _output = [[ AVCaptureMetadataOutput alloc ] init ];
    [ _output setMetadataObjectsDelegate : self queue : dispatch_get_main_queue ()];
    // Session
    _session = [[ AVCaptureSession alloc ] init ];
    [ _session setSessionPreset : AVCaptureSessionPresetHigh ];
    if ([ _session canAddInput : self.input ])
    {
        [ _session addInput : self.input ];
    }
    if ([ _session canAddOutput : self.output ])
    {
        [ _session addOutput : self.output ];
    }
    // 条码类型 AVMetadataObjectTypeQRCode
    _output . metadataObjectTypes = @[ AVMetadataObjectTypeQRCode ] ;
    // Preview
    _preview =[ AVCaptureVideoPreviewLayer layerWithSession : _session ];
    _preview . videoGravity = AVLayerVideoGravityResizeAspectFill ;
    _preview . frame = self.view.frame;
    [ self . view . layer insertSublayer : _preview atIndex : 0 ];
    //扫描区域框
    [ _session startRunning ];
    
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(10, 40, 30, 30)];
    [btn setImage:[UIImage imageNamed:@"cjfh"] forState:UIControlStateNormal];
    btn.tag = 99;
    [self.view addSubview:btn];
    [btn addTarget:self action:@selector(backActino:) forControlEvents:UIControlEventTouchUpInside];
    
    if (!_isview) {
        UIButton *fwbtn = [[UIButton alloc]initWithFrame:CGRectMake(70, 40, 30, 30)];
        [fwbtn setImage:[UIImage imageNamed:@"cjfw"] forState:UIControlStateNormal];
        [self.view addSubview:fwbtn];
        [fwbtn addTarget:self action:@selector(fwActino:) forControlEvents:UIControlEventTouchUpInside];
    }
    [self insetItem];
}
-(CGPoint)setxy{
    CGFloat x1 = [self getRandomNumber:40 to:SCRE_WIDTH - 40];
    CGFloat y = [self getRandomNumber:140 to:SCRE_HEIGHT-50];
    return  CGPointMake(x1, y);
}
-(void)insetItem{
    d = [NSMutableArray array];
    db = [NSMutableArray array];
    b = [NSMutableArray array];
    xb = [NSMutableArray array];
    x = [NSMutableArray array];
    xn = [NSMutableArray array];
    n = [NSMutableArray array];
    dn = [NSMutableArray array];
    MyLatLng *m1 = [[MyLatLng alloc]init];//当前坐标
    NSMutableDictionary *userLocation = [UserDefaults readUserDefaultObjectValueForKey:@"userLocation"];
    [m1 initData:[[NSString stringWithFormat:@"%@",[userLocation objectForKey:@"lat"]] floatValue] ln:[[NSString stringWithFormat:@"%@",[userLocation objectForKey:@"lng"]] floatValue]];
    NSLog(@"xhw->SceneVC->ary.count%lu",(unsigned long)ary.count);
    for (int i = 0; i<ary.count; i++) {
        LoginResponseModel *user =  [ary objectAtIndex:i];
        NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
        if(_isuser){
            [dic setObject:user.nickname forKey:@"name"];
            [dic setObject:user.uid forKey:@"id"];
            [dic setObject:user.headsmall forKey:@"headsmall"];
            [dic setObject:user.isfriend forKey:@"isfriend"];
        }else{
            [dic setObject:user.name forKey:@"name"];
            [dic setObject:user.id forKey:@"id"];
        }
        [dic setObject:user.lng forKey:@"lo"];
        [dic setObject:user.lat forKey:@"la"];
        [dic setObject:user.distance forKey:@"distance"];
        MyLatLng *m2= [[MyLatLng alloc]init];
        [m2 initData:[[dic objectForKey:@"la"] floatValue] ln:[[dic objectForKey:@"lo"]floatValue]];
        NSMutableDictionary * direction = [ValidateHelper outFangxiang:m1 b:m2];
        NSString *w = [direction objectForKey:@"p"];
        NSMutableDictionary *newdic = [[NSMutableDictionary alloc]init];
        [newdic addEntriesFromDictionary:direction];
        [newdic addEntriesFromDictionary:dic];
        dic = newdic;
        if ([w isEqualToString:@"东"]) {
            CGPoint center = [self setxy];
            [dic setObject:[NSString stringWithFormat:@"%f",center.x] forKey:@"x"];
            [dic setObject:[NSString stringWithFormat:@"%f",center.y] forKey:@"y"];
            [d addObject:dic];
        }
        if ([w isEqualToString:@"东北"]) {
            CGPoint center = [self setxy];
            [dic setObject:[NSString stringWithFormat:@"%f",center.x] forKey:@"x"];
            [dic setObject:[NSString stringWithFormat:@"%f",center.y] forKey:@"y"];
            [db addObject:dic];
        }
        if ([w isEqualToString:@"北"]) {
            CGPoint center = [self setxy];
            [dic setObject:[NSString stringWithFormat:@"%f",center.x] forKey:@"x"];
            [dic setObject:[NSString stringWithFormat:@"%f",center.y] forKey:@"y"];
            [b addObject:dic];
        }
        if ([w isEqualToString:@"西北"]) {
            CGPoint center = [self setxy];
            [dic setObject:[NSString stringWithFormat:@"%f",center.x] forKey:@"x"];
            [dic setObject:[NSString stringWithFormat:@"%f",center.y] forKey:@"y"];
            [xb addObject:dic];
        }
        if ([w isEqualToString:@"西"]) {
            CGPoint center = [self setxy];
            [dic setObject:[NSString stringWithFormat:@"%f",center.x] forKey:@"x"];
            [dic setObject:[NSString stringWithFormat:@"%f",center.y] forKey:@"y"];
            [x addObject:dic];
        }
        if ([w isEqualToString:@"西南"]) {
            CGPoint center = [self setxy];
            [dic setObject:[NSString stringWithFormat:@"%f",center.x] forKey:@"x"];
            [dic setObject:[NSString stringWithFormat:@"%f",center.y] forKey:@"y"];
            [xn addObject:dic];
        }
        if ([w isEqualToString:@"南"]) {
            CGPoint center = [self setxy];
            [dic setObject:[NSString stringWithFormat:@"%f",center.x] forKey:@"x"];
            [dic setObject:[NSString stringWithFormat:@"%f",center.y] forKey:@"y"];
            [n addObject:dic];
        }
        if ([w isEqualToString:@"东南"]) {
            CGPoint center = [self setxy];
            [dic setObject:[NSString stringWithFormat:@"%f",center.x] forKey:@"x"];
            [dic setObject:[NSString stringWithFormat:@"%f",center.y] forKey:@"y"];
            [dn addObject:dic];
        }
    }
    
    //缩略图上的点
    for (int i=0; i<d.count; i++) {
        UIView *views = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 2, 2)];
        views.backgroundColor = [UIColor whiteColor];
        views.layer.cornerRadius = 1;
        int jd = [[[d objectAtIndex:i] objectForKey:@"jd"] intValue];
        views.tag = jd;
        CGPoint center = [self calcCircleCoordinateWithCenter:mapview.center andWithAngle:jd andWithRadius:20];
        views.center = CGPointMake(center.x, center.y);
        [mapview addSubview:views];
    }
    for (int i=0; i<db.count; i++) {
        UIView *views = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 2, 2)];
        views.backgroundColor = [UIColor whiteColor];
        views.layer.cornerRadius = 1;
        int jd = [[[db objectAtIndex:i] objectForKey:@"jd"] intValue];
        views.tag = jd;
        CGPoint center =[self calcCircleCoordinateWithCenter:mapview.center andWithAngle:jd andWithRadius:20];
        views.center = CGPointMake(center.x, center.y);
        [mapview addSubview:views];
    }
    for (int i=0; i<b.count; i++) {
        UIView *views = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 2, 2)];
        
        views.backgroundColor = [UIColor whiteColor];
        views.layer.cornerRadius = 1;
        int jd = [[[b objectAtIndex:i] objectForKey:@"jd"] intValue];
        views.tag = jd;
        CGPoint center = [self calcCircleCoordinateWithCenter:mapview.center andWithAngle:jd andWithRadius:20];
        views.center = CGPointMake(center.x, center.y);
        [mapview addSubview:views];
    }
    for (int i=0; i<xb.count; i++) {
        UIView *views = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 2, 2)];
        views.backgroundColor = [UIColor whiteColor];
        views.layer.cornerRadius = 1;
        int jd = [[[xb objectAtIndex:i] objectForKey:@"jd"] intValue];
        views.tag = jd;
        CGPoint center = [self calcCircleCoordinateWithCenter:mapview.center andWithAngle:jd andWithRadius:-20];
        views.center = CGPointMake(center.x, center.y);
        [mapview addSubview:views];
    }
    for (int i=0; i<x.count; i++) {
        UIView *views = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 2, 2)];
        views.backgroundColor = [UIColor whiteColor];
        views.layer.cornerRadius = 1;
        int jd = [[[x objectAtIndex:i] objectForKey:@"jd"] intValue];
        views.tag = jd;
        CGPoint center = [self calcCircleCoordinateWithCenter:mapview.center andWithAngle:jd+70 andWithRadius:-20];
        views.center = CGPointMake(center.x, center.y);
        [mapview addSubview:views];
    }
    for (int i=0; i<xn.count; i++) {
        UIView *views = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 2, 2)];
        views.backgroundColor = [UIColor whiteColor];
        views.layer.cornerRadius = 1;
        CGFloat jd = [[[xn objectAtIndex:i] objectForKey:@"jd"] intValue];
        views.tag = jd;
        CGPoint center = [self calcCircleCoordinateWithCenter:mapview.center andWithAngle:jd andWithRadius:-20];
        views.center = CGPointMake(center.x, center.y);
        [mapview addSubview:views];
    }
    for (int i=0; i<n.count; i++) {
        UIView *views = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 2, 2)];
        views.backgroundColor = [UIColor whiteColor];
        views.layer.cornerRadius = 1;
        int jd = [[[n objectAtIndex:i] objectForKey:@"jd"] intValue];
        views.tag = jd;
        CGPoint center = [self calcCircleCoordinateWithCenter:mapview.center andWithAngle:jd andWithRadius:-20];
        views.center = CGPointMake(center.x, center.y);
        [mapview addSubview:views];
    }
    for (int i=0; i<dn.count; i++) {
        UIView *views = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 2, 2)];
        views.backgroundColor = [UIColor whiteColor];
        views.layer.cornerRadius = 1;
        int jd = [[[dn objectAtIndex:i] objectForKey:@"jd"] intValue];
        views.tag = jd;
        CGPoint center =[self calcCircleCoordinateWithCenter:mapview.center andWithAngle:jd andWithRadius:-20];
        views.center = CGPointMake(center.x, center.y);
        [mapview addSubview:views];
    }
    
    NSLog(@"%@",mapview.subviews);
    
    //collection全景
    self.views = [NSMutableArray array];
    
    //北
    UIView *view = [[UIView alloc] initWithFrame:self.view.bounds];
    for(int i= 0;i<b.count;i++){
        if (_isuser) {
            [view addSubview:[self addUserView:b i:i wz:@"b"]];
        }else{
            [view addSubview:[self addServiceView:b i:i]];
        }
    }
    NSLog(@"北:view.subViews->%@",view.subviews);
    [self.views addObject:view];
    //东北
    view = [[UIView alloc] initWithFrame:self.view.bounds];
    for(int i= 0;i<db.count;i++){
        if (_isuser) {
            [view addSubview:[self addUserView:db i:i wz:@"db"]];
        }else{
            [view addSubview:[self addServiceView:db i:i]];
        }
    }
    NSLog(@"东北:view.subViews->%@",view.subviews);
    [self.views addObject:view];
    //东
    view = [[UIView alloc] initWithFrame:self.view.bounds];
    for(int i= 0;i<d.count;i++){
        if (_isuser) {
            [view addSubview:[self addUserView:d i:i wz:@"d"]];
        }else{
            [view addSubview:[self addServiceView:d i:i]];
        }
    }
    NSLog(@"东:view.subViews->%@",view.subviews);
    [self.views addObject:view];
    //东南
    view = [[UIView alloc] initWithFrame:self.view.bounds];
    for(int i= 0;i<dn.count;i++){
        if (_isuser) {
            [view addSubview:[self addUserView:dn i:i wz:@"dn"]];
        }else{
            [view addSubview:[self addServiceView:dn i:i]];
        }
    }
    NSLog(@"东南:view.subViews->%@",view.subviews);
    [self.views addObject:view];
    //南
    view = [[UIView alloc] initWithFrame:self.view.bounds];
    for(int i= 0;i<n.count;i++){
        if (_isuser) {
            [view addSubview:[self addUserView:n i:i wz:@"n"]];
        }else{
            [view addSubview:[self addServiceView:n i:i]];
        }
    }
    NSLog(@"南:view.subViews->%@",view.subviews);
    [self.views addObject:view];
    //西南
    view = [[UIView alloc] initWithFrame:self.view.bounds];
    for(int i= 0;i<xn.count;i++){
        if (_isuser) {
            [view addSubview:[self addUserView:xn i:i wz:@"xn"]];
        }else{
            [view addSubview:[self addServiceView:xn i:i]];
        }
    }
    NSLog(@"西南:view.subViews->%@",view.subviews);
    [self.views addObject:view];
    //西
    view = [[UIView alloc] initWithFrame:self.view.bounds];
    for(int i= 0;i<x.count;i++){
        if (_isuser) {
            [view addSubview:[self addUserView:x i:i wz:@"x"]];
        }else{
            [view addSubview:[self addServiceView:x i:i]];
        }
    }
    NSLog(@"西:view.subViews->%@",view.subviews);
    [self.views addObject:view];
    //西北
    view = [[UIView alloc] initWithFrame:self.view.bounds];
    for(int i= 0;i<xb.count;i++){
        if (_isuser) {
            [view addSubview:[self addUserView:xb i:i wz:@"xb"]];
        }else{
            [view addSubview:[self addServiceView:xb i:i]];
        }
    }
    NSLog(@"西北:view.subViews->%@",view.subviews);
    [self.views addObject:view];
    
    NSLog(@"SceneVC->self.views.count->%lu",(unsigned long)self.views.count);
    
    [self.collectionView reloadData];
    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:50] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
    
    self.jiaoduToOffset = 8.0 * SCRE_WIDTH / 360.0;
}

- (void)xhwFullSence {
    //collection全景
    self.views = [NSMutableArray array];
    //北
    UIView *view = [[UIView alloc] initWithFrame:self.view.bounds];
    for(int i= 0;i<b.count;i++){
        if (_isuser) {
            [view addSubview:[self addUserView:b i:i wz:@"b"]];
        }else{
            [view addSubview:[self addServiceView:b i:i]];
        }
    }
    [self.views addObject:view];
    //东北
    view = [[UIView alloc] initWithFrame:self.view.bounds];
    for(int i= 0;i<db.count;i++){
        if (_isuser) {
            [view addSubview:[self addUserView:db i:i wz:@"db"]];
        }else{
            [view addSubview:[self addServiceView:db i:i]];
        }
    }
    [self.views addObject:view];
    //东
    view = [[UIView alloc] initWithFrame:self.view.bounds];
    for(int i= 0;i<d.count;i++){
        if (_isuser) {
            [view addSubview:[self addUserView:d i:i wz:@"d"]];
        }else{
            [view addSubview:[self addServiceView:d i:i]];
        }
    }
    [self.views addObject:view];
    //东南
    view = [[UIView alloc] initWithFrame:self.view.bounds];
    for(int i= 0;i<dn.count;i++){
        if (_isuser) {
            [view addSubview:[self addUserView:dn i:i wz:@"dn"]];
        }else{
            [view addSubview:[self addServiceView:dn i:i]];
        }
    }
    [self.views addObject:view];
    //南
    view = [[UIView alloc] initWithFrame:self.view.bounds];
    for(int i= 0;i<n.count;i++){
        if (_isuser) {
            [view addSubview:[self addUserView:n i:i wz:@"n"]];
        }else{
            [view addSubview:[self addServiceView:n i:i]];
        }
    }
    [self.views addObject:view];
    //西南
    view = [[UIView alloc] initWithFrame:self.view.bounds];
    for(int i= 0;i<xn.count;i++){
        if (_isuser) {
            [view addSubview:[self addUserView:xn i:i wz:@"xn"]];
        }else{
            [view addSubview:[self addServiceView:xn i:i]];
        }
    }
    [self.views addObject:view];
    //西
    view = [[UIView alloc] initWithFrame:self.view.bounds];
    for(int i= 0;i<x.count;i++){
        if (_isuser) {
            [view addSubview:[self addUserView:x i:i wz:@"x"]];
        }else{
            [view addSubview:[self addServiceView:x i:i]];
        }
    }
    [self.views addObject:view];
    //西北
    view = [[UIView alloc] initWithFrame:self.view.bounds];
    for(int i= 0;i<xb.count;i++){
        if (_isuser) {
            [view addSubview:[self addUserView:xb i:i wz:@"xb"]];
        }else{
            [view addSubview:[self addServiceView:xb i:i]];
        }
    }
    [self.views addObject:view];
    

}

#pragma mark - 转动方向时响应
-(void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading
{
    //每次要重置view的位置，才能保证图片每次偏转量正常，而不是叠加，指针方向正确。
    mapview.transform = CGAffineTransformIdentity;
    
    CGFloat headings = -1.0f * M_PI * newHeading.magneticHeading / 180;
    mapview.transform = CGAffineTransformMakeRotation(headings);
    CLLocationDirection jiaodu = newHeading.trueHeading;
    
    la.text=[[NSString alloc]initWithFormat:@"%.2f",newHeading.magneticHeading];
//    UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation;
//    if(!UIDeviceOrientationIsPortrait(deviceOrientation)){
//        return;
//    }
    
    /***
     * 360度中每一度就对应collection偏移  8 * SCRE_WIDTH / 360
     * 338度对应偏移量为0，0度对应偏移量为SCRE_WIDTH/2,  22度对应偏移量为SCRE_WIDTH,
    ***/
    
    
    //根据方向滑动collectionView 实现360全景效果
    
    //由角度计算对应的collection偏移量
    static CLLocationDirection oldJD = 0;

    if (oldJD == 0) {
//        第一次定位角度
        CGFloat jiaoduOffset = jiaodu * _jiaoduToOffset + SCRE_WIDTH/2;
        self.collectionView.mj_offsetX = 49 * 8 * SCRE_WIDTH + jiaoduOffset;
    } else {
        //转动实现相对上次位置
        //顺时针
        if ((jiaodu > oldJD && !(oldJD == 0 && jiaodu > 364)) || (oldJD > 364 && jiaodu == 0)) {
            if (jiaodu == 0) {
                self.collectionView.mj_offsetX += (365-oldJD) * _jiaoduToOffset;
            } else {
                self.collectionView.mj_offsetX += (jiaodu-oldJD) * _jiaoduToOffset;
            }
        }
        //逆时针
        else {
            if (oldJD == 0) {
                self.collectionView.mj_offsetX -= (365 - jiaodu) * _jiaoduToOffset;
            } else {
                self.collectionView.mj_offsetX -= (oldJD - jiaodu) * _jiaoduToOffset;
            }
        }
    }
    NSLog(@"%f-%f",oldJD,jiaodu);
    oldJD = jiaodu;
}
#pragma mark 添加用户 item
-(UIView *)addUserView:(NSMutableArray *)aryi i:(int)i wz:(NSString *)wz{
    UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(5, 0, 60, 60)];
    [ValidateHelper setImage:[[aryi objectAtIndex:i] objectForKey:@"headsmall"] img:img istoux:YES];
    img.layer.cornerRadius = img.frame.size.width/2;
    img.clipsToBounds = YES;
    int isf = [[[aryi objectAtIndex:i] objectForKey:@"isfriend"] intValue];
    UIImage *image1 = [UIImage imageNamed:isf==1?@"cj_sc_on":@"cj_sc_off"];
    
    UIImage *image2 = [UIImage imageNamed:@"cjdh"];
    UIImage *image3 = [UIImage imageNamed:@"cjgr"];
    NSArray *images = @[image1, image2, image3];
    SphereMenu *sphereMenu = [[SphereMenu alloc] initWithStartPoint:CGPointMake([[[aryi objectAtIndex:i] objectForKey:@"x"] floatValue], [[[aryi objectAtIndex:i] objectForKey:@"y"] floatValue])
                                                         startImage:img
                                                      submenuImages:images];
    sphereMenu.uid = [[aryi objectAtIndex:i] objectForKey:@"id"];
    sphereMenu.wz = wz;
    sphereMenu.delegate = self;
    //xhw11月10号加
    sphereMenu.tag = [[[aryi objectAtIndex:i] objectForKey:@"id"] intValue];
    NSString *ds1 = [[aryi objectAtIndex:i] objectForKey:@"distance"];
    int s =[ds1 intValue]/1000;
    NSString *di = [NSString stringWithFormat:@"%d",s];
    CGSize ds = [ValidateHelper sizeOfText:[ValidateHelper DistanceFormat:di] theFont:[UIFont systemFontOfSize:14]];
    
    UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(5, 60, ds.width+10, 15)];
    lab.font = [UIFont systemFontOfSize:12];
    lab.textColor = [UIColor grayColor];
    lab.textAlignment = NSTextAlignmentCenter;
    lab.text = [ValidateHelper DistanceFormat:di];
    lab.layer.cornerRadius = 8;
    lab.clipsToBounds = YES;
    lab.layer.opacity = 0.5;
    lab.backgroundColor = colorBG;
    [sphereMenu addSubview:lab];
    return sphereMenu;
}
#pragma mark 添加服务 item
-(UIView *)addServiceView:(NSMutableArray *)aryi i:(int)i{
    NSLog(@"走到添加服务这里了");
    NSString *ds1 = [[aryi objectAtIndex:i] objectForKey:@"distance"];
    int s =[ds1 intValue]/1000;
    NSString *di = [NSString stringWithFormat:@"%d",s];
    CGSize ds = [ValidateHelper sizeOfText:[ValidateHelper DistanceFormat:di] theFont:[UIFont systemFontOfSize:14]];
    
    CGSize g = [ValidateHelper sizeOfText:[[aryi objectAtIndex:i] objectForKey:@"name"] theFont:[UIFont systemFontOfSize:14]];
    if (ds.width<g.width) {
        ds.width = g.width;
    }else{
        ds.width = ds.width;
    }
    BaseButton *view = [[BaseButton alloc]initWithFrame:CGRectMake([[[aryi objectAtIndex:i] objectForKey:@"x"] floatValue],[[[aryi objectAtIndex:i] objectForKey:@"y"] floatValue], ds.width+30, 60)];
    view.tag = i;
    view.layer.cornerRadius = 6;
    view.dic = [aryi objectAtIndex:i];
    [view addTarget:self action:@selector(selectAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *bgview= [[UIButton alloc]initWithFrame:CGRectMake(0, 0, view.frame.size.width, 30)];
    bgview.backgroundColor = UIColorFromRGB(0x667C6D);
    
    
    //TODO:uiview 单边圆角或者单边框
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:bgview.bounds byRoundingCorners:(UIRectCornerTopRight | UIRectCornerTopLeft) cornerRadii:CGSizeMake(5,5)];//圆角大小
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = bgview.bounds;
    maskLayer.path = maskPath.CGPath;
    bgview.layer.mask = maskLayer;
    //将view上的所有子视图的用户交互关闭,因为UIView的用户交互默认都是打开的(xhw11月10号加)
    bgview.userInteractionEnabled = NO;
    [view addSubview:bgview];
    
    UIImageView *bimgb = [[UIImageView alloc]initWithFrame:CGRectMake(0, 30,view.frame.size.width, 30)];
    bimgb.image = [UIImage imageNamed:@"cjxia"];
    bimgb.userInteractionEnabled = NO;
    [view addSubview:bimgb];
    
    
    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, view.frame.size.width, 30)];
    title.textAlignment = NSTextAlignmentCenter;
    title.text = [[aryi objectAtIndex:i] objectForKey:@"name"];
    title.font = [UIFont systemFontOfSize:14];
    title.textColor = [UIColor whiteColor];
    title.userInteractionEnabled = NO;
    [view addSubview:title];
    
    
    UIImageView *dimg = [[UIImageView alloc]initWithFrame:CGRectMake(5, 30+(30/2-12/2)/2, 11, 12)];
    dimg.image = [UIImage imageNamed:@"cjdimg"];
    dimg.userInteractionEnabled = NO;
    [view addSubview:dimg];
    
    UILabel *distance = [[UILabel alloc]initWithFrame:CGRectMake(20, 26, ds.width, 30)];
    distance.text = [ValidateHelper DistanceFormat:di];
    distance.font = [UIFont systemFontOfSize:14];
    distance.textAlignment = NSTextAlignmentCenter;
    distance.textColor = [UIColor whiteColor];
    distance.userInteractionEnabled = NO;
    [view addSubview:distance];
    NSLog(@"%@",view.subviews);
    return view;
}


#pragma mark 选中服务
-(void)selectAction:(BaseButton *)btn{
    map = btn.dic;
    UIActionSheet *alrt = [[UIActionSheet alloc]initWithTitle:@"导航" delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:@"使用系统地图导航",@"使用高德地图导航",@"使用百度地图导航",@"取消", nil];
    [alrt showInView:self.view];
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSMutableDictionary *userLocation = [UserDefaults readUserDefaultObjectValueForKey:@"userLocation"];
    
    BOOL hasBaiduMap = NO;
    BOOL hasGaodeMap = NO;
    
    if ([[UIApplication sharedApplication]canOpenURL:[NSURL URLWithString:@"baidumap://"]]){
        hasBaiduMap = YES;
    }
    if ([[UIApplication sharedApplication]canOpenURL:[NSURL URLWithString:@"iosamap://"]]){
        hasGaodeMap = YES;
    }
    if(buttonIndex == 0){
        NSString *string =[NSString stringWithFormat:@"http://maps.apple.com/maps?saddr=%@,%@&daddr=%@,%@",[userLocation objectForKey:@"lat"],[userLocation objectForKey:@"lng"],[map objectForKey:@"la"],[map objectForKey:@"lo"]];
        [[UIApplication sharedApplication]  openURL:[NSURL URLWithString:string]];
    }else if(buttonIndex == 1){
        NSString *urlString = [[NSString stringWithFormat:@"iosamap://navi?sourceApplication=%@&backScheme=%@&poiname=%@&lat=%f&lon=%f&dev=1&style=2",@"app name", @"一米社交", @"终点", [[map objectForKey:@"la"] doubleValue], [[map objectForKey:@"lo"] doubleValue]] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        if (!hasBaiduMap) {
            [SVProgressHUD showImage:nil status:@"当前未安装高德地图"];
        }else{
            [[UIApplication sharedApplication]openURL:[NSURL URLWithString:urlString]];
        }
        
    }else if(buttonIndex == 2){
        NSString *urlString = [[NSString stringWithFormat:@"baidumap://map/direction?origin=latlng:%@,%@|name:我的位置&destination=latlng:%@,%@|name:终点&mode=driving",[userLocation objectForKey:@"lat"], [userLocation objectForKey:@"lng"],[map objectForKey:@"la"],[map objectForKey:@"lo"]] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] ;
        if (!hasBaiduMap) {
            [SVProgressHUD showImage:nil status:@"当前未安装百度地图"];
        }else{
            [[UIApplication sharedApplication]openURL:[NSURL URLWithString:urlString]];
        }
    }
}

#pragma mark 关注、对话、详情按钮点击事件
- (void)sphereDidSelected:(int)index id:(int)uid wz:(NSString *)wz
{
    NSLog(@"sphere %d selected", index);

    if(index == 0 ){//关注
        [[AppDelegate shareDelegate]refuser:[NSString stringWithFormat:@"%d",uid] success:^(id as) {
            LoginResponseModel *user = as;
            NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
            if ([user.isfriend intValue]==0) {
                [dic setObject:@"0" forKey:@"type"];
            }else{
                [dic setObject:@"1" forKey:@"type"];
            }
            [dic setObject:user.uid forKey:@"fid"];
            [[BusinessService shareInstance]follow:dic success:^(id result) {
                [SVProgressHUD showImage:nil status:@"成功"];
                NSMutableArray *wzary = nil;
                if ([wz isEqualToString:@"d"]) {
                    wzary = d;
                }
                if ([wz isEqualToString:@"db"]) {
                    wzary = db;
                }
                if ([wz isEqualToString:@"b"]) {
                    wzary = b;
                }
                if ([wz isEqualToString:@"xb"]) {
                    wzary = xb;
                }
                if ([wz isEqualToString:@"x"]) {
                    wzary = x;
                }
                if ([wz isEqualToString:@"n"]) {
                    wzary = n;
                }
                if ([wz isEqualToString:@"dn"]) {
                    wzary = dn;
                }
                
                //之前的代码少了一个西南(xhw11月10号加）
                if ([wz isEqualToString:@"xn"]) {
                    wzary = xn;
                }

                for (int  i = 0; i<wzary.count; i++) {
                    NSMutableDictionary *dic = [wzary objectAtIndex:i];
                    [wzary removeObjectAtIndex:i];
                    if ([[dic objectForKey:@"id"] intValue] == uid) {
                        [dic setObject:[[dic objectForKey:@"isfriend"] intValue]==1?@"0":@"1" forKey:@"isfriend"];
                        [wzary insertObject:dic atIndex:i];
                    }
                }
                if ([wz isEqualToString:@"d"]) {
                    d = wzary;
                }
                if ([wz isEqualToString:@"db"]) {
                    db = wzary;
                }
                if ([wz isEqualToString:@"b"]) {
                    b = wzary;
                }
                if ([wz isEqualToString:@"xb"]) {
                    xb = wzary;
                }
                if ([wz isEqualToString:@"x"]) {
                    x = wzary;
                }
                if ([wz isEqualToString:@"n"]) {
                    n = wzary;
                }
                if ([wz isEqualToString:@"dn"]) {
                    dn = wzary;
                }
                //之前的代码少了一个西南(xhw11月10号加）
                if ([wz isEqualToString:@"xn"]) {
                    xn = wzary;
                }
                
                //之前点击了关注之后界面上的关注按钮没有变化,现在加了下面两行刷新界面的代码(xhw11月10号加)
                [self xhwFullSence];
                [self.collectionView reloadData];
                
                
                [locationManager startUpdatingHeading];
            } failure:^(id result) {
                [SVProgressHUD showErrorWithStatus:result];
            }];
        }];
    }
    if(index == 1 ){//对话
        [[AppDelegate shareDelegate]refuser:[NSString stringWithFormat:@"%d",uid] success:^(id as) {
            LoginResponseModel *user = as;
            UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"MS"
                                                                         bundle:[NSBundle mainBundle]];
            ChatViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"ChatVC"];
            searchResultDetailController.user = user;
            [self.navigationController pushViewController:searchResultDetailController animated:YES];
        }];
        
        
        
    }
    if (index == 2) {//详情
        DTModel *mode = [[DTModel alloc]init];
        mode.uid = [NSString stringWithFormat:@"%d",uid];
        UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"MS"
                                                                     bundle:[NSBundle mainBundle]];
        FriendDetailsMainVC *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"FriendDetailsMainVC"];
        searchResultDetailController.model = mode;
        [self.navigationController pushViewController:searchResultDetailController animated:YES];
    }
}
-(BOOL)locationManagerShouldDisplayHeadingCalibration:(CLLocationManager *)manager
{
    return YES;
}

- (IBAction)backActino:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma MARK 点击搜索按钮
- (IBAction)fwActino:(id)sender {
    UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"FJ"
                                                                 bundle:[NSBundle mainBundle]];
    UIViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"ServiceVC"];
    [self.navigationController pushViewController:searchResultDetailController animated:YES];
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 100;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.views.count;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(SCRE_WIDTH, SCRE_HEIGHT);
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ImageCell" forIndexPath:indexPath];
    [cell qmui_removeAllSubviews];
    UIView *xhwView = self.views[indexPath.item];
    NSLog(@"%lu",(long)indexPath.item);
    NSLog(@"collectionViewCell->self.views[indexPath.item]->%@",self.views[indexPath.item]);
    NSLog(@"collectionViewCell->self.views[indexPath.item]->self.views[indexPath.item].subViews->%@",xhwView.subviews);
    NSLog(@"collectionViewCell->self.views[indexPath.item]->self.views[indexPath.item].subViews->%@",xhwView.subviews);
    [cell addSubview:self.views[indexPath.item]];
    return cell;
}


@end
